<!--帮助文档管理-->
<template>
  <div class="app-container flex-row">
    <!-- 左侧树 -->
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:290px">
      <div class="common-title">
        <h2>帮助文档分类</h2>
      </div>
      <el-input v-model="searchValue" placeholder="请输入分类名称进行搜索" style="margin-top:10px" />
      <el-tree
        ref="tree"
        v-loading="treeLoading"
        class="common-el-tree"
        :data="treeData"
        :props="defaultTreeProps"
        :accordion="true"
        :expand-on-click-node="false"
        :default-expand-all="true"
        :highlight-current="true"
        :filter-node-method="onTreeFilter"
        :default-checked-keys="checkedKeys"
        style="margin-top:10px"
        node-key="id"
        @node-click="handleNodeClick">
        <span slot-scope="{ node }" class="custom-tree-node">
          <i class="el-icon-notebook-2" />
          <span class="text">{{ node.data.name }}</span>
        </span>
      </el-tree>
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.categoryName" placeholder="请单击左侧某个节点" disabled />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.title" placeholder="请输入帮助文档标题" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
        </div>
        <!--列表-->
        <el-table
          ref="articleTable"
          :data="articleList"
          header-cell-class-name="table-header"
          fit
          highlight-current-row
          height="100%"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="50" />
          <el-table-column :show-overflow-tooltip="true" label="文章标题" prop="title" sortable min-width="150">
            <template slot-scope="scope">
              <span class="color-primary common-cursor" @click="handleLook(scope.row.id)">{{ scope.row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orders" sortable label="排序" width="160" />
          <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
            <template slot-scope="scope">
              {{ scope.row.gmtModified | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination_handler">
        <pagination v-show="articleTotal > 0" :total="articleTotal" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>

    <side-box :show="sideBox.show" :title="sideBox.title" :width="'calc(100% - 20px)'" class="side-modal-box-full" @close="sideBox.show = !sideBox.show">
      <template slot="body">
        <el-form ref="dataForm" :rules="articleRules" :model="articleRecord" label-position="right" label-width="120px">
          <!--<el-form-item label="封面:" prop="photo">
            <single-image-upload ref="logo" v-model="articleRecord.photo" :catalog="constants.FILE_CATALOG_HELP_LOGO" />
          </el-form-item>-->
          <el-form-item label="标题:" prop="title"><el-input v-model="articleRecord.title" maxlength="50" show-word-limit placeholder="请输入" /></el-form-item>
          <el-form-item label="分类:" prop="categoryName">
            <el-input v-model="articleRecord.categoryName" placeholder="请单击左侧某个节点" disabled />
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="articleRecord.orders" placeholder="请输入" style="width:100%" show-word-limit :min="1" :max="9999" maxlength="4" />
          </el-form-item>
          <el-form-item label="内容:" prop="content" class="ue-container">
            <Editor v-model="articleRecord.content" :catalog="constants.FILE_CATALOG_HELP_CONTENT" />
          </el-form-item>
          <el-form-item label="附件:" prop="attachment1">
            <simple-uploader v-model="articleRecord.attachment1" :mode="['file']" :catalog="constants.FILE_CATALOG_HELP_ATTACHMENT" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button :loading="sideBox.buttonLoading" plain type="primary" @click="sideBox.status === 'create' ? createData() : updateData()">保存</el-button>
      </template>
    </side-box>
  </div>
</template>

<script>

export default {
  components: { },
  data() {
    return {
      treeLoading: false,
      checkedKeys: [],
      searchValue: '',
      defaultTreeProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      treeData: [],
      articleList: [],
      articleTotal: 0,
      multipleSelectionRecords: [],
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        title: '',
        sort: '-orders'
      },
      sideBox: {
        show: false,
        title: '',
        status: 'create',
        buttonLoading: false
      },
      articleRecord: {
        photo: '',
        title: '',
        categoryId: '',
        content: '',
        attachment: ''
      },
      articleRules: {
        photo: [{ required: true, message: '请上传封面', trigger: 'blur' }],
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        categoryName: [{ required: true, message: '请选择分类', trigger: 'blur' }]
      }
    }
  },
  watch: {
    searchValue(val) {
      this.$refs.tree.filter(val)
    },

    'listQuery.organizationCategory': function(val) {
      this.initOrgCategory()
    }
  },
  created() {
    // this.fetchData()
    this.treeLoading = true
    this.fetchCategoryData()
  },
  methods: {
    fetchCategoryData() {
      this.$store.dispatch('upmsCategoryDictTreeByType', '01').then((res) => {
        this.treeLoading = false
        this.treeData = res
        if (this.treeData.length > 0) {
          this.handleNodeClick(this.treeData[0])
        }
      }).catch((_) => {
        this.treeLoading = false
      })
    },
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultTreeProps.filter] ? data[this.defaultTreeProps.label].indexOf(value) !== -1 || data[this.defaultTreeProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultTreeProps.label].indexOf(value) !== -1
    },
    handleNodeClick(data) {
      this.checkedKeys.length = 0
      this.checkedKeys.push(data.id)
      console.log(data.id)
      this.$refs.tree.setCheckedKeys(this.checkedKeys)
      this.listQuery.categoryName = data.name
      this.listQuery.categoryId = data.id
      this.handleFilter()
    },
    // 上传附件成功
    uploadSuccess() {
      console.log('// 上传附件成功')
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        title: '',
        sort: '-orders'
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('helpArticlePage', this.listQuery)
      this.articleList = response.records
      this.articleTotal = response.total
    },
    /**
     * 排序规则
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    /**
     * 全选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },

    handleRowClick(row) {
      this.$refs.articleTable.toggleRowSelection(row)
    },
    handleCreate() {
      this.articleRecord = {
        categoryName: this.listQuery.categoryName,
        orders: 9999,
        attachment1: []
      }
      this.sideBox.status = 'create'
      this.sideBox.show = true
      this.sideBox.title = '新增帮助文档'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.articleRecord.categoryId = this.listQuery.categoryId
          const tempData = Object.assign({}, this.articleRecord)
          tempData.attachment = tempData.attachment1.join(',')
          delete tempData.attachment1

          this.$store.dispatch('saveHelpArticle', tempData).then(response => {
            this.sideBox.show = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.show = true
          })
        }
      })
    },
    handleUpdate(row) {
      this.articleRecord = Object.assign({}, row)
      this.articleRecord = {
        ...this.articleRecord,
        attachment1: this.articleRecord.attachment === null ? [] : this.articleRecord.attachment.split(',')
      }
      this.sideBox.status = 'update'
      this.sideBox.show = true
      this.sideBox.title = '编辑[' + this.articleRecord.title + ']'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$store.dispatch('getHelpContentDetailsById', row.id).then(res => {
          this.articleRecord = {
            ...this.articleRecord,
            categoryName: res.categoryName,
            content: res.content == null ? '' : res.content
          }
        }).catch(() => {})
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.articleRecord)
          tempData.attachment = tempData.attachment1.join(',')
          delete tempData.attachment1
          this.$store.dispatch('updateHelpArticle', tempData).then(response => {
            this.sideBox.show = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.show = true
          })
        }
      })
    },
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.articleTable.clearSelection()
      this.$refs.articleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removehelpArticle', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => {})
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },
    handleLook(id) {
      window.open(this.$router.resolve({ path: '/upms/system/help/details/' + id }).href)
    }
  }
}
</script>

<style lang="scss" scoped></style>
